package cc.lj.internal.core.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 使用@JsonSerialize格式化BigDecimal解决.00不显示问题
 * 在DTO返回给前端的字段上使用 @JsonSerialize(using = BigDecimalSerialize.class), 价格返回给前端就会自动加上.00
  * @author liangxifeng
 * @date 2022/7/13 11:25
 */
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (value != null && !"".equals(value)) {
            gen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_DOWN) + "");
        } else {
            gen.writeString(value + "");
        }
    }
}